<template>
  <div class="file-list">
    <h2>File List</h2>
    <el-table :data="files">
      <el-table-column prop="file_name" label="File Name"></el-table-column>
      <el-table-column label="Actions">
        <template v-slot="scope">
          <el-button @click="downloadFile(scope.row.file_name)">Download</el-button>
          <el-button type="danger" @click="deleteFile(scope.row.file_name)">Delete</el-button>
        </template>
      </el-table-column>
      <el-table-column label="Download Progress">
        <template v-slot="scope">
          <el-progress :percentage="scope.row.downloadProgress"></el-progress>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { eventBus } from '@/eventBus.js';

export default {
  name: 'FileList',
  data() {
    return {
      files: [],
      downloadProgress: 0
    }
  },
  async created() {
    await this.fetchFiles()
  },
  mounted() {
    eventBus.on('file uploaded', this.fetchFiles);
  },
  beforeUnmount() {
    eventBus.off('file uploaded', this.fetchFiles);
  },
  methods: {
    async fetchFiles() {
      try {
        const response = await axios.get('/list')
        if (response.data.success) {
          this.files = response.data.files.map(file_name => ({ file_name, downloadProgress: 0 }))
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        ElMessage.error('Failed to fetch file list')
      }
    },
    async downloadFile(fileName) {
      const file = this.files.find(f => f.file_name === fileName);
      if (!file) return;

      try {
        file.downloadProgress = 0;
        const response = await axios.get(`/download?file_name=${fileName}`, {
          responseType: 'blob',
          onDownloadProgress: (progressEvent) => {
            file.downloadProgress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          }
        });
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
      } catch (error) {
        ElMessage.error('Failed to download file');
        file.downloadProgress = 0; // Reset progress on error
      }
    },
    async deleteFile(fileName) {
      try {
        const response = await axios.post(`/delete?file_name=${fileName}`,)
        if (response.data.success) {
          ElMessage.success('File deleted successfully')
          await this.fetchFiles()
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        ElMessage.error('Failed to delete file')
      }
    }
  }
}
</script>

<style scoped>
.file-list {
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
</style>